#include "messagepackage.h"

messagePackage::messagePackage()
{

}

void messagePackage::setMessage(const QJsonObject &value)
{
    message = value;
}

void messagePackage::setMessage(const QByteArray byte)
{
    message = QJsonDocument::fromJson(byte).object();
}

void messagePackage::setMessage(const QString str)
{
    message = QJsonDocument::fromJson(str.toUtf8()).object();
}

void messagePackage::setType(messagePackage::Type type)
{
    message["type"] = type;
}

messagePackage::Type messagePackage::type() const
{
    return static_cast<Type>(message["type"].toInt());
}

void messagePackage::setUserName(QString name)
{
    message["userName"] = name;
}

QString messagePackage::UserName()
{
    return message["userName"].toString();
}

void messagePackage::setUserPassword(QString pswd)
{
    message["userPassword"] = pswd;
}

QString messagePackage::userPassword()
{
    return message["userPassword"].toString();
}

QByteArray messagePackage::toByteArray() const
{
    QJsonDocument doc(message);
    return doc.toJson();
}

void messagePackage::setRet(bool ret)
{
    message["return"] = ret;
}

bool messagePackage::Ret() const
{
    return message["return"].toBool();
}



void messagePackage::sendMessage(const messagePackage *msg, QTcpSocket *socket)
{
    QByteArray sendByte = msg->toByteArray();
    int len = sendByte.size();

    socket->write((char*)&len,sizeof(int));
    socket->write(sendByte);
}

messagePackage messagePackage::recvMessage(QTcpSocket *socket)
{
    int len ;
    socket->read((char*)&len,sizeof(int));
    QByteArray recvByte = socket->read(len);

    messagePackage message;
    message.setMessage(recvByte);
    return message;
}
